Page({
  data: {
    phone: '',
    canLogin: false,
  },

  onInputPhone(e) {
    const phone = e.detail.value;
    this.setData({
      phone,
      canLogin: phone.length === 11
    });
  },

  async onLogin() {
    const { phone } = this.data;

    wx.cloud.callFunction({
      name: 'getOpenId',
      success: async res => {
        const { openid, session_key } = res.result;

        const db = wx.cloud.database();
        const userRes = await db.collection('user').where({ openid }).get();

        if (userRes.data.length === 0) {
          await db.collection('user').add({
            data: {
              phone,
              openid,
              session_key,
              isLogin: true
            }
          });
        } else {
          await db.collection('user').doc(userRes.data[0]._id).update({
            data: {
              phone,
              session_key,
              isLogin: true
            }
          });
        }

        wx.showToast({
          title: '登录成功',
          icon: 'success'
        });

        wx.reLaunch({
          url: '/pages/market/market'
        });

        wx.switchTab({
          url: '/pages/selfStock/selfStock'
        });
        
      },
      fail: err => {
        console.error('❌ 获取 openid 失败:', err);
        wx.showToast({ title: '获取 openid 失败', icon: 'error' });
      }
    });
  }
});
